package org.fujene.sandbox;

import java.io.IOException;

import junit.framework.TestCase;

import org.msgpack.MessagePackObject;
import org.msgpack.object.ArrayType;
import org.msgpack.object.IntegerType;
import org.msgpack.rpc.Client;
import org.msgpack.rpc.Request;
import org.msgpack.rpc.Server;
import org.msgpack.rpc.loop.EventLoop;

public class TestMsgpackOverhead extends TestCase{
	public static class TestHandler{
		public void test(Request req) {
			MessagePackObject[] obj = new MessagePackObject[100000];
			for(int i = 0; i < obj.length; i++){
				obj[i] = IntegerType.create(i);
			}
			req.sendResult(ArrayType.create(obj));
		}
	}
	
	public static void testMsgpack() throws IOException {
		System.out.print("Establishing server...");
		EventLoop loop = EventLoop.defaultEventLoop();
		Server server = new Server(loop);
		server.serve(new TestHandler());
		server.listen(45000);
		System.out.println(" Done.");
		
		long time = System.nanoTime();
		System.out.print("Loop with new client");
		for(int i = 0; i < 10000; i++){
			Client client = new Client("localhost", 45000);
			client.callApply("test", new Object[] {});
			client.close();
			if(i % 500 == 0) System.out.print(".");
		}
		System.out.println(" Done.");
		System.out.println("***Time: " + ((System.nanoTime() - time) / 1000000.0) + " ms / 10000 loops");

		time = System.nanoTime();
		System.out.print("Loop with one client");
		Client client = new Client("localhost", 45000);
		for(int i = 0; i < 10000; i++){
			client.callApply("test", new Object[] {});
			if(i % 500 == 0) System.out.print(".");
		}
		client.close();
		System.out.println(" Done.");
		System.out.println("***Time: " + ((System.nanoTime() - time) / 1000000.0) + " ms / 10000 loops");
	}
}
